package com.atguigu.gmall.oms.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.oms.entity.OrderItemEntity;
import com.atguigu.gmall.oms.feign.GmallPmsClient;
import com.atguigu.gmall.oms.mapper.OrderItemMapper;
import com.atguigu.gmall.oms.vo.OrderItemVo;
import com.atguigu.gmall.oms.vo.OrderSubmitVO;
import com.atguigu.gmall.pms.entity.BrandEntity;
import com.atguigu.gmall.pms.entity.SkuEntity;
import com.atguigu.gmall.pms.entity.SpuDescEntity;
import com.atguigu.gmall.pms.entity.SpuEntity;
import com.atguigu.gmall.ums.entity.UserAddressEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.oms.mapper.OrderMapper;
import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.oms.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Transactional
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderEntity> implements OrderService {

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private GmallPmsClient pmsClient;


    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<OrderEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<OrderEntity>()
        );

        return new PageResultVo(page);
    }

    @Transactional
    @Override
    public OrderEntity saveOrder(OrderSubmitVO orderSubmitVO, Long userId) {
        // 保存订单
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSubmitVO.getOrderToken());
        orderEntity.setCreateTime(new Date());
        orderEntity.setUserId(userId);
        orderEntity.setTotalAmount(orderSubmitVO.getTotalPrice());
        orderEntity.setPayAmount(orderSubmitVO.getTotalPrice());
        orderEntity.setPayType(orderSubmitVO.getPayType());
        orderEntity.setStatus(0);
        orderEntity.setConfirmStatus(0);
        orderEntity.setDeliveryCompany(orderSubmitVO.getDeliveryCompany());
        UserAddressEntity address = orderSubmitVO.getAddress();
        if (address != null) {
            orderEntity.setReceiverCity(address.getCity());
            orderEntity.setReceiverAddress(address.getAddress());
            orderEntity.setReceiverPhone(address.getPhone());
            orderEntity.setReceiverName(address.getName());
            orderEntity.setReceiverPostCode(address.getPostCode());
            orderEntity.setReceiverRegion(address.getPhone());
            orderEntity.setReceiverProvince(address.getProvince());
        }

        this.save(orderEntity);
        Long orderId = orderEntity.getId();

        // 保存订单详情
        List<OrderItemVo> orderItems = orderSubmitVO.getItems();
        if (CollectionUtils.isEmpty(orderItems)) {
            return null;
        }
        orderItems.forEach(item -> {
            OrderItemEntity orderItemEntity = new OrderItemEntity();
            // 订单信息
            orderItemEntity.setOrderId(orderId);
            orderItemEntity.setOrderSn(orderEntity.getOrderSn());
            orderItemEntity.setSkuQuantity(item.getCount().intValue());  //数量
            orderItemEntity.setSkuAttrsVals(JSON.toJSONString(item.getSaleAttrs()));
            // 先查询sku相关信息
            Long skuId = item.getSkuId();
            ResponseVo<SkuEntity> skuEntityResponseVo = this.pmsClient.querySkuById(skuId);
            SkuEntity skuEntity = skuEntityResponseVo.getData();
            if (skuEntity != null) {
                orderItemEntity.setSkuId(skuId);
                orderItemEntity.setSkuName(skuEntity.getName());
                orderItemEntity.setSkuPrice(skuEntity.getPrice());
                orderItemEntity.setSkuPic(skuEntity.getDefaultImage());
                orderItemEntity.setCategoryId(skuEntity.getCategoryId());
            }

            // 查询品牌信息
            ResponseVo<BrandEntity> brandEntityResponseVo = this.pmsClient.queryBrandById(skuEntity.getBrandId());
            BrandEntity brandEntity = brandEntityResponseVo.getData();
            if (brandEntity != null) {
                orderItemEntity.setSpuBrand(brandEntity.getName());
            }

            // 查询spu
            ResponseVo<SpuEntity> spuEntityResponseVo = this.pmsClient.querySpuById(skuEntity.getSpuId());
            SpuEntity spuEntity = spuEntityResponseVo.getData();
            if (spuEntity != null) {
                orderItemEntity.setSpuId(spuEntity.getId());
                orderItemEntity.setSpuName(spuEntity.getName());

            }

            // 查询描述信息
            ResponseVo<SpuDescEntity> spuDescEntityResponseVo = this.pmsClient.querySpuDescById(skuEntity.getSpuId());
            SpuDescEntity spuDescEntity = spuDescEntityResponseVo.getData();
            if (spuDescEntity != null) {
                orderItemEntity.setSpuPic(spuDescEntity.getDecript());
            }

            orderItemEntity.setRealAmount(skuEntity.getPrice());

            //TODO 查询优惠信息


            this.orderItemMapper.insert(orderItemEntity);
        });


        return orderEntity;
    }

}